package com.ghy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.relation.RelationManager;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.ghy.constant.ML;
import com.ghy.dto.BannerInsertDTO;
import com.ghy.dto.BannerPageDTO;
import com.ghy.dto.BannerUpdateDTO;
import com.ghy.entity.Banner;

import com.ghy.exception.ServiceException;
import com.ghy.mapper.BannerMapper;
import com.ghy.service.BannerService;
import com.ghy.util.MinioUtil;
import com.ghy.vo.BannerSimpleListVO;
import org.springframework.stereotype.Service;
import com.mybatisflex.core.paginate.Page;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;

import java.util.List;

import static com.ghy.entity.table.BannerTableDef.BANNER;

/**
 * 横幅表 服务层实现。
 *
 * @author ghy
 * @since 2024-12-22
 */
@Service
@CacheConfig(cacheNames = "banner")
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner>  implements BannerService{


    @CacheEvict(allEntries = true)
    @Override
    public boolean insert(BannerInsertDTO dto) {
        //组装entity 实体类
        Banner banner = BeanUtil.copyProperties(dto, Banner.class);

        banner.setCreated(LocalDateTime.now());
        banner.setUpdated(LocalDateTime.now());
        banner.setUrl(ML.Banner.DEFAULT_BANNER);

        return mapper.insert(banner) > 0;
    }


    @Cacheable(key = "#p0",
            condition = "#p0 != null",
            unless = "#result == null")
    @Override
    public Banner select(Long id) {
        RelationManager.addQueryRelations("episode");
        return mapper.selectOneWithRelationsById(id);
    }

    @Cacheable(key = "#root.methodName",
            unless = "#result == null")
    @Override
    public List<BannerSimpleListVO> simpleList() {
        return QueryChain.of(mapper)
                .withRelations ()
                .listAs(BannerSimpleListVO.class);
    }

    @Cacheable(key ="#root.methodName + ':' + #p0.toString()",
            condition = "#p0 != null",
            unless = "#result == null")
    @Override
    public Page<Banner> page(BannerPageDTO dto) {
        QueryChain<Banner> queryChain = QueryChain.of(mapper);

        return queryChain.withRelations()
                .page(new Page<>(dto.getPageNum(),dto.getPageSize()));
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean update(BannerUpdateDTO dto) {
        //组装entity实体类
        Banner banner = BeanUtil.copyProperties(dto, Banner.class);

        banner.setUpdated(LocalDateTime.now());

        return UpdateChain.of(banner)
                .where(BANNER.ID.eq(banner.getId()))
                .update();
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean delete(Long id) {

        //删除父评论
        return mapper.deleteById(id) > 0;

    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteBatch(List<Long> ids) {

        //删除父评论
        return mapper.deleteBatchByIds(ids) > 0;
    }

    @CacheEvict(allEntries = true)
    @Cacheable(key = "#root.methodName", unless = "#result == null")
    @Override
    public List<Banner> top(Long n) {
        return QueryChain.of(mapper)
                .orderBy(BANNER.IDX.asc(), BANNER.ID.desc())
                .limit(n)
                .withRelations()
                .list();
    }

    @Override
    @CacheEvict(allEntries = true)
    public String uploadBanner(MultipartFile bannerFile, Long id) {
        //按主键查询用户记录
        Banner banner = mapper.selectOneById(id);
        if (ObjectUtil.isNull(banner)) {
            throw new ServiceException("横幅不存在");
        }
        //备份旧头像
        String oldUrl = banner.getUrl();
        //重新生成文件名
        String filename = MinioUtil.randomFilename(bannerFile);
        //根据用户主键修改用户头像
        banner.setUrl(filename);
        if (mapper.update(banner) <= 0) {
            throw new ServiceException("头像更新失败：DB操作异常");
        }
        try {
            //从MinIO中删除旧头像：默认头像不删除
            if (!ML.Banner.DEFAULT_BANNER.contains(oldUrl)) {
                MinioUtil.delete(oldUrl, ML.MinIO.BANNER_DIR, ML.MinIO.BUCKET_NAME);
            }
            //向MinIO中上传新头像
            MinioUtil.upload(bannerFile, filename, ML.MinIO.BANNER_DIR, ML.MinIO.BUCKET_NAME);
        }catch(Exception e) {
            throw new ServiceException("图片更新失败：MinIo操作异常");
        }

        //返回文件名
        return filename;


    }

}
